//
//  HOVoiceDownloader.m
//  微度报修
//
//  Created by foguo-mac-1 on 7/6/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOVoiceDownloader.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "HOUtils.h"
#import "VoiceConverter.h"
#import "HOUIMgr.h"
#import "HOConstants.h"

static HOVoiceDownloader *instance;


@interface HOVoiceDownloader()
{
	NSMutableDictionary *dataDic;
}
@end
@implementation HOVoiceDownloader
+ (HOVoiceDownloader *)sharedInstance
{
	if(instance == nil)
	{
		instance = [[HOVoiceDownloader alloc] init];
	}
	return instance;
}
- (NSData *)getDataWithURL:(NSString *)fileUrl
{
	return [dataDic objectForKey:fileUrl];
}

+ (NSString *)getFileNameFromURL:(NSString *)url
{
	NSArray *array = [url componentsSeparatedByString:@"//"];
	if([array count] != 2)
		return @"";
	NSArray *subArray = [[array objectAtIndex:1] componentsSeparatedByString:@"/"];
	NSString *fileName = [subArray lastObject];
	NSArray *fileNameArray = [fileName componentsSeparatedByString:@"."];
	if([fileNameArray count] == 0)
		return @"";
	return [fileNameArray firstObject];
	
}

- (void)downloadFielWithURL:(NSString *)fileUrl
{
	if([HOUtils getValideString:fileUrl].length == 0)
		return;
		
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
		
		NSURL *url = [NSURL URLWithString:fileUrl];
		NSError *error = nil;
		NSData *wavData = nil;
		NSString *fileName = [HOVoiceDownloader getFileNameFromURL:fileUrl];
		NSString *filePath = [HOUtils getFilePathWithFileName:fileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:@"wav"];
		wavData = [NSData dataWithContentsOfFile:filePath];
//		NSLog(@"wavData:%@", wavData);
		if(wavData != nil)
		{
			dispatch_async(dispatch_get_main_queue(), ^{
				[[HOUIMgr sharedInstance] sendCommand:kHO_CMD_voiceDidDownload data:fileUrl];
			});;
		}
		else
		{
			NSData * amrData = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&error];
			wavData = [VoiceConverter amrToWavWithAmrData:amrData];
			[HOUtils saveAudioIntLocal:wavData withFilePath:filePath];
			wavData = nil;
			dispatch_async(dispatch_get_main_queue(), ^{
				[[HOUIMgr sharedInstance] sendCommand:kHO_CMD_voiceDidDownload data:fileUrl];
			});
		}
		
	});
	
}

- (void)cleanup
{
	[dataDic removeAllObjects];
}

- (instancetype)init
{
	self = [super init];
	if(self)
	{
		dataDic = [[NSMutableDictionary alloc] init];
	}
	return self;
}
@end
